<template>
  <div class="grading-assistant">
    <div class="page-header">
      <h1>AI评分助手</h1>
      <p>使用AI技术智能评分，提供详细的反馈和建议</p>
    </div>

    <el-row :gutter="24">
      <!-- 评分配置 -->
      <el-col :span="8">
        <el-card class="grading-config">
          <template #header>
            <span>评分配置</span>
          </template>

          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
          >
            <el-form-item label="评分类型" prop="grading_type">
              <el-radio-group v-model="form.grading_type" @change="onGradingTypeChange">
                <el-radio-button label="essay">作文评分</el-radio-button>
                <el-radio-button label="short_answer">简答题评分</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <!-- 作文评分配置 -->
            <template v-if="form.grading_type === 'essay'">
              <el-form-item label="作文题目" prop="essay_prompt">
                <el-input
                  v-model="form.essay_prompt"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入作文题目或要求"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="评分标准">
                <el-input
                  v-model="form.rubric"
                  type="textarea"
                  :rows="4"
                  placeholder="可选：输入具体的评分标准"
                  maxlength="1000"
                  show-word-limit
                />
              </el-form-item>
            </template>

            <!-- 简答题评分配置 -->
            <template v-if="form.grading_type === 'short_answer'">
              <el-form-item label="题目" prop="question">
                <el-input
                  v-model="form.question"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入题目内容"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="参考答案">
                <el-input
                  v-model="form.reference_answer"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入参考答案"
                  maxlength="1000"
                  show-word-limit
                />
              </el-form-item>
            </template>

            <el-form-item label="满分" prop="max_score">
              <el-input-number
                v-model="form.max_score"
                :min="1"
                :max="100"
                :step="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="学生答案" prop="student_answer">
              <el-input
                v-model="form.student_answer"
                type="textarea"
                :rows="6"
                placeholder="请输入学生的答案内容"
                maxlength="5000"
                show-word-limit
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                :loading="grading"
                @click="gradeAnswer"
                :disabled="!canGrade"
              >
                <el-icon><View /></el-icon>
                {{ grading ? '评分中...' : '开始评分' }}
              </el-button>
              <el-button @click="resetForm">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button @click="loadExample">
                <el-icon><Document /></el-icon>
                加载示例
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 评分历史 -->
        <el-card class="grading-history" style="margin-top: 20px;">
          <template #header>
            <span>最近评分记录</span>
          </template>

          <div class="history-list">
            <div
              v-for="record in gradingHistory"
              :key="record.id"
              class="history-item"
              @click="loadHistoryRecord(record)"
            >
              <div class="history-header">
                <span class="history-type">
                  {{ getGradingTypeText(record.grading_type) }}
                </span>
                <span class="history-score">
                  {{ record.ai_score }}/{{ record.max_score }}
                </span>
              </div>
              <div class="history-time">
                {{ formatTime(record.created_at) }}
              </div>
            </div>
          </div>

          <div v-if="gradingHistory.length === 0" class="empty-history">
            暂无评分记录
          </div>
        </el-card>
      </el-col>

      <!-- 评分结果 -->
      <el-col :span="16">
        <el-card class="grading-results">
          <template #header>
            <div class="results-header">
              <span>评分结果</span>
              <div class="actions" v-if="gradingResult">
                <el-button
                  type="success"
                  size="small"
                  @click="saveGradingResult"
                >
                  <el-icon><Check /></el-icon>
                  保存结果
                </el-button>
                <el-button
                  size="small"
                  @click="exportResult"
                >
                  <el-icon><Download /></el-icon>
                  导出报告
                </el-button>
                <el-button
                  size="small"
                  @click="provideFeedback"
                >
                  <el-icon><ChatDotRound /></el-icon>
                  反馈评分
                </el-button>
              </div>
            </div>
          </template>

          <!-- 加载状态 -->
          <div v-if="grading" class="loading-state">
            <el-progress
              :percentage="gradingProgress"
              :status="gradingStatus"
            />
            <p style="text-align: center; margin-top: 20px;">
              {{ gradingStatusText }}
            </p>
          </div>

          <!-- 空状态 -->
          <el-empty
            v-else-if="!grading && !gradingResult"
            description="暂无评分结果，请配置参数后开始评分"
          />

          <!-- 评分结果展示 -->
          <div v-else-if="gradingResult" class="result-content">
            <!-- 总体评分 -->
            <div class="score-overview">
              <div class="score-circle">
                <el-progress
                  type="circle"
                  :percentage="scorePercentage"
                  :width="120"
                  :stroke-width="8"
                  :color="getScoreColor(scorePercentage)"
                >
                  <template #default="{ percentage }">
                    <span class="score-text">{{ gradingResult.score }}/{{ form.max_score }}</span>
                  </template>
                </el-progress>
              </div>
              <div class="score-info">
                <h3>综合评分</h3>
                <p>{{ getScoreLevel(gradingResult.score_percentage) }}</p>
                <el-tag :type="getScoreTagType(gradingResult.score_percentage)">
                  {{ Math.round(gradingResult.score_percentage) }}%
                </el-tag>
              </div>
            </div>

            <!-- 详细反馈 -->
            <div class="detailed-feedback">
              <h4>详细评语</h4>
              <div class="feedback-content">
                {{ gradingResult.detailed_feedback }}
              </div>
            </div>

            <!-- 优点分析 -->
            <div class="strengths-section">
              <h4>
                <el-icon><Star /></el-icon>
                优点分析
              </h4>
              <ul class="strengths-list">
                <li v-for="(strength, index) in gradingResult.strengths" :key="index">
                  {{ strength }}
                </li>
              </ul>
            </div>

            <!-- 不足分析 -->
            <div class="weaknesses-section">
              <h4>
                <el-icon><Warning /></el-icon>
                改进建议
              </h4>
              <ul class="weaknesses-list">
                <li v-for="(weakness, index) in gradingResult.weaknesses" :key="index">
                  {{ weakness }}
                </li>
              </ul>
            </div>

            <!-- 具体建议 -->
            <div class="suggestions-section">
              <h4>
                <el-icon><Lightbulb /></el-icon>
                学习建议
              </h4>
              <div class="suggestions-list">
                <div
                  v-for="(suggestion, index) in gradingResult.suggestions"
                  :key="index"
                  class="suggestion-item"
                >
                  {{ index + 1 }}. {{ suggestion }}
                </div>
              </div>
            </div>

            <!-- AI置信度 -->
            <div class="confidence-info">
              <el-alert
                :title="`AI评分置信度：${getConfidenceText()}%`"
                type="info"
                :closable="false"
                show-icon
              >
                <template #default>
                  <p>AI评分结果仅供参考，建议结合人工评分进行综合判断。</p>
                </template>
              </el-alert>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 反馈对话框 -->
    <el-dialog
      v-model="feedbackVisible"
      title="评分反馈"
      width="500px"
    >
      <el-form :model="feedbackForm" label-width="80px">
        <el-form-item label="满意度">
          <el-rate
            v-model="feedbackForm.satisfaction"
            :texts="['很不满意', '不满意', '一般', '满意', '很满意']"
            show-text
          />
        </el-form-item>
        <el-form-item label="反馈意见">
          <el-input
            v-model="feedbackForm.feedback"
            type="textarea"
            :rows="4"
            placeholder="请输入您的反馈意见"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="feedbackVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFeedback">提交反馈</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  View, Refresh, Document, Check, Download, ChatDotRound,
  Star, Warning, Lightbulb
} from '@element-plus/icons-vue'
import { aiApi, type GradingRequest, type GradingResult } from '@/api/ai'

// 响应式数据
const grading = ref(false)
const gradingProgress = ref(0)
const gradingStatus = ref<'success' | 'exception' | ''>('')
const gradingStatusText = ref('')
const gradingResult = ref<GradingResult | null>(null)
const gradingHistory = ref<any[]>([])
const feedbackVisible = ref(false)

// 表单数据
const form = ref<GradingRequest>({
  grading_type: 'essay',
  student_answer: '',
  // Essay fields
  essay_prompt: '',
  rubric: '',
  max_score: 100,
  // Short answer fields
  question: '',
  reference_answer: ''
})

// 反馈表单
const feedbackForm = ref({
  satisfaction: 3,
  feedback: ''
})

// 表单验证规则
const rules = {
  grading_type: [
    { required: true, message: '请选择评分类型', trigger: 'change' }
  ],
  student_answer: [
    { required: true, message: '请输入学生答案', trigger: 'blur' }
  ],
  essay_prompt: [
    { required: true, message: '请输入作文题目', trigger: 'blur' }
  ],
  question: [
    { required: true, message: '请输入题目', trigger: 'blur' }
  ],
  max_score: [
    { required: true, message: '请输入满分', trigger: 'blur' }
  ]
}

// 计算属性
const canGrade = computed(() => {
  if (!form.value.student_answer) return false
  if (form.value.grading_type === 'essay') {
    return !!form.value.essay_prompt
  }
  if (form.value.grading_type === 'short_answer') {
    return !!form.value.question
  }
  return false
})

const scorePercentage = computed(() => {
  if (!gradingResult.value) return 0
  return Math.round((gradingResult.value.score / form.value.max_score) * 100)
})

// 方法
const onGradingTypeChange = (type: string) => {
  gradingResult.value = null
  // 重置相关字段
  if (type === 'essay') {
    form.value.question = ''
    form.value.reference_answer = ''
  } else {
    form.value.essay_prompt = ''
    form.value.rubric = ''
  }
}

const gradeAnswer = async () => {
  try {
    grading.value = true
    gradingProgress.value = 0
    gradingStatus.value = ''
    gradingStatusText.value = '正在分析答案...'

    const response = await aiApi.gradeAnswer(form.value)

    if (response.success) {
      gradingProgress.value = 100
      gradingStatus.value = 'success'
      gradingStatusText.value = '评分完成'
      gradingResult.value = response.grading
      ElMessage.success('AI评分完成')
      await loadGradingHistory()
    } else {
      throw new Error(response.error || '评分失败')
    }
  } catch (error: any) {
    gradingProgress.value = 0
    gradingStatus.value = 'exception'
    gradingStatusText.value = '评分失败'
    ElMessage.error(error.message || 'AI评分失败')
  } finally {
    grading.value = false
  }
}

const resetForm = () => {
  form.value = {
    grading_type: 'essay',
    student_answer: '',
    essay_prompt: '',
    rubric: '',
    max_score: 100,
    question: '',
    reference_answer: ''
  }
  gradingResult.value = null
}

const loadExample = () => {
  if (form.value.grading_type === 'essay') {
    form.value.essay_prompt = '请以"我的梦想"为题写一篇作文，不少于600字。'
    form.value.rubric = '评分标准：内容主题明确(30%)，结构完整(25%)，语言流畅(25%)，创意新颖(20%)'
    form.value.student_answer = '我的梦想是成为一名科学家。从小我就对科学充满了好奇，每当看到科学实验的神奇现象，我都会激动不已...'
  } else {
    form.value.question = '请简述光合作用的过程和意义。'
    form.value.reference_answer = '光合作用是植物利用光能将二氧化碳和水转化为有机物的过程...'
    form.value.student_answer = '光合作用是植物的一个重要生理过程...'
  }
}

const saveGradingResult = () => {
  if (!gradingResult.value) return

  // 这里应该调用后端API保存评分结果
  ElMessage.success('评分结果已保存')
}

const exportResult = () => {
  if (!gradingResult.value) return

  const content = `
评分报告
==========================================

评分类型：${getGradingTypeText(form.value.grading_type)}
得分：${gradingResult.value.score}/${form.value.max_score}
百分比：${Math.round(gradingResult.value.score_percentage)}%

详细评语：
${gradingResult.value.detailed_feedback}

优点：
${gradingResult.value.strengths.map((s, i) => `${i + 1}. ${s}`).join('\n')}

改进建议：
${gradingResult.value.weaknesses.map((w, i) => `${i + 1}. ${w}`).join('\n')}

学习建议：
${gradingResult.value.suggestions.map((s, i) => `${i + 1}. ${s}`).join('\n')}
  `.trim()

  const blob = new Blob([content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `AI评分报告_${new Date().toLocaleDateString()}.txt`
  link.click()
  URL.revokeObjectURL(url)
}

const provideFeedback = () => {
  feedbackVisible.value = true
}

const submitFeedback = async () => {
  try {
    await aiApi.submitFeedback({
      satisfaction: feedbackForm.value.satisfaction,
      feedback: feedbackForm.value.feedback
    })
    ElMessage.success('反馈提交成功')
    feedbackVisible.value = false
  } catch (error) {
    ElMessage.error('反馈提交失败')
  }
}

const loadGradingHistory = async () => {
  try {
    // 这里应该调用后端API获取评分历史
    // const history = await aiApi.getGradingHistory()
    // gradingHistory.value = history
  } catch (error) {
    console.error('加载评分历史失败:', error)
  }
}

const loadHistoryRecord = (record: any) => {
  // 加载历史记录到表单
  Object.assign(form.value, record)
  gradingResult.value = record
}

const getScoreColor = (percentage: number) => {
  if (percentage >= 90) return '#67c23a'
  if (percentage >= 80) return '#e6a23c'
  if (percentage >= 60) return '#f56c6c'
  return '#909399'
}

const getScoreLevel = (percentage: number) => {
  if (percentage >= 90) return '优秀'
  if (percentage >= 80) return '良好'
  if (percentage >= 70) return '中等'
  if (percentage >= 60) return '及格'
  return '不及格'
}

const getScoreTagType = (percentage: number) => {
  if (percentage >= 90) return 'success'
  if (percentage >= 80) return 'warning'
  if (percentage >= 60) return 'danger'
  return 'info'
}

const getConfidenceText = () => {
  // 模拟AI置信度
  return 85 + Math.floor(Math.random() * 10)
}

const getGradingTypeText = (type: string) => {
  const texts = {
    essay: '作文评分',
    short_answer: '简答题评分'
  }
  return texts[type] || type
}

const formatTime = (time: string) => {
  return new Date(time).toLocaleString()
}

// 生命周期
onMounted(() => {
  loadGradingHistory()
})
</script>

<style scoped>
.grading-assistant {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-header p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.grading-config {
  height: fit-content;
}

.grading-history {
  margin-top: 20px;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  padding: 12px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.history-item:hover {
  border-color: #3b82f6;
  background-color: #f0f9ff;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.history-type {
  font-weight: 500;
  color: #374151;
}

.history-score {
  color: #3b82f6;
  font-weight: 600;
}

.history-time {
  font-size: 12px;
  color: #6b7280;
}

.empty-history {
  text-align: center;
  color: #6b7280;
  padding: 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  display: flex;
  gap: 8px;
}

.loading-state {
  padding: 40px 20px;
}

.result-content {
  max-height: 600px;
  overflow-y: auto;
}

.score-overview {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  margin-bottom: 24px;
}

.score-text {
  font-size: 16px;
  font-weight: 600;
  color: white;
}

.score-info h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
}

.score-info p {
  margin: 0 0 12px 0;
  opacity: 0.9;
}

.detailed-feedback,
.strengths-section,
.weaknesses-section,
.suggestions-section {
  margin-bottom: 24px;
}

.detailed-feedback h4,
.strengths-section h4,
.weaknesses-section h4,
.suggestions-section h4 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

.feedback-content {
  padding: 16px;
  background-color: #f9fafb;
  border-radius: 8px;
  line-height: 1.6;
  color: #4b5563;
}

.strengths-list,
.weaknesses-list {
  margin: 0;
  padding-left: 20px;
}

.strengths-list li,
.weaknesses-list li {
  margin-bottom: 8px;
  line-height: 1.5;
  color: #4b5563;
}

.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.suggestion-item {
  padding: 12px;
  background-color: #f0f9ff;
  border-left: 4px solid #3b82f6;
  border-radius: 6px;
  line-height: 1.5;
  color: #1e40af;
}

.confidence-info {
  margin-top: 24px;
}

@media (max-width: 768px) {
  .grading-assistant {
    padding: 16px;
  }

  .el-col {
    margin-bottom: 16px;
  }

  .score-overview {
    flex-direction: column;
    text-align: center;
  }

  .actions {
    flex-direction: column;
    width: 100%;
  }
}
</style>